<template>
  <div>
    <Content :style="{minHeight: '400px'}">
      <div class="layout-content">
        <Affix>
          <div class="page-header shadow">
            <span class="pull-left title"><Icon type="ios-book-outline"></Icon> 试卷编辑 <small>(尚未上传至资料库)</small></span>
            <div class="pull-right">
              <ul>
                <li><Button type="text" icon="plus" size="small" @click="unshiftSubject">添加一题</Button></li>
                <li><Button type="text" icon="printer" size="small">保存</Button></li>
                <li><Button type="text" icon="pie-graph" size="small">统计</Button></li>
                <li><Button type="text" icon="ios-cloud-upload" size="small">导入</Button></li>
              </ul>
            </div>
          </div>
        </Affix>
        <Modal
          :closable="false"
          :width="650"
          :mask-closable="false"
          v-model="editorBool"
          :title="modalTitle[modalType]"
          @on-ok="modalAppend"
          @on-cancel="modalCancel">
          <div id="editorElem"></div>
        </Modal>
        <div v-for="(item, index) in subject" :class="err && index === 0? 'error': ''" class="subject active" :key="index">
          <div class="active-checkmark"></div>
          <Icon type="android-done"></Icon>
          <div class="subject-close">
            <Poptip
              confirm
              title="删除无法恢复哦！"
              placement="bottom-end"
              @on-ok="handleDel(index)">
              <Icon type="close"></Icon>
            </Poptip>
          </div>

          <div class="title">
            <span class="pull-left num">{{ index + 1 }}</span>
            <div class="pull-left mar-r-20">
              <span>题型：</span>
              <Select v-model="item.type" style="width:100px" @on-change="changeType($event, index)">
                <Option v-for="item1 in subjectTypeList" :value="item1.value" :key="item1.value">{{ item1.label }}</Option>
              </Select>
            </div>
            <div class="pull-left mar-r-20">
              <span>资源编号：</span>
              <span>Q1072830</span>
            </div>

            <div class="pull-left mar-r-20">
              <span>知识点：</span>
              <Select v-model="knowledge" style="width:100px" placeholder="其他">
                <Option v-for="item2 in knowledgeList" :value="item2.value" :key="item2.value">{{ item2.label }}</Option>
              </Select>
            </div>

            <div class="pull-left mar-r-20">
              <InputNumber :max="100" :min="1" v-model="item.score"></InputNumber>
              <span>分</span>
            </div>

            <div class="pull-right mar-r-20">
              <Button type="success">保存</Button>
            </div>
          </div>

          <div class="question" @click="showModal('question', index)">
            <div v-if="item.question" v-html="item.question"></div>
            <span v-else class="null">还没有题干，点击此处 <span class="text-blue">添加题干</span></span>
          </div>

          <div class="answer" v-if="item.type == 1 || item.type == 2">
            <RadioGroup v-model="radioAnswer" vertical v-if="item.type == 1">
              <Radio :label="letter[idx]" v-for="(item3, idx) in item.answer" :key="idx">
                  <span
                    class="null"
                    v-if="item3 === ''"
                    @click.stop.prevent="showModal('answer', index, idx)">
                    <span>{{letter[idx]}}、 还未有选项内容，点击此处</span>
                    <span class="text-blue">添加内容</span>
                  </span>
                <span
                  class="answer-item"
                  v-else
                  @click.stop.prevent="showModal('answer', index, idx)">
                  <span>{{letter[idx]}}、</span>
                  <span v-html="item3"></span>
                </span>
                <span @click.stop.prevent="handleDelAnswer(index, idx)"><Icon type="close" class="answer-close"></Icon></span>
              </Radio>
            </RadioGroup>

            <CheckboxGroup v-model="checkboxAnswer" class="inline" v-if="item.type == 2">
              <Checkbox :label="letter[idx]" v-for="(item3, idx) in item.answer" :key="idx">
                <span
                  class="null"
                  v-if="item3 === ''"
                  @click.stop.prevent="showModal('answer', index, idx)">
                    <span>{{letter[idx]}}、 还未有选项内容，点击此处</span>
                    <span class="text-blue">添加内容</span>
                  </span>
                <span
                  class="answer-item"
                  v-else
                  @click.stop.prevent="showModal('answer', index, idx)">
                  <span>{{letter[idx]}}、</span>
                  <span v-html="item3"></span>
                </span>
                <span @click.stop.prevent="handleDelAnswer(index, idx)"><Icon type="close" class="answer-close"></Icon></span>
              </Checkbox>
            </CheckboxGroup>

            <div class="append-answer"><Button @click="handleAppendAnswer(index)" type="text" class="text-blue" icon="plus" size="small">添加一个选项</Button></div>

          </div>

          <div class="line"></div>

          <div class="subject-content">
            <p class="title">解析内容</p>
            <div class="content" @click="showModal('content', index)">
              <div v-if="item.content" v-html="item.content"></div>
              <div v-else><span class="null">还没有解析，点击此处 <span class="text-blue">添加解析</span></span></div>
            </div>
          </div>
        </div>
        <div v-if="!subject.length" class="nothing" @click="unshiftSubject">
          <p>还没有题目 <span class="text-blue">添加题目</span></p>
        </div>
      </div>

    </Content>
  </div>
</template>
<script>
  import E from 'wangeditor'
  import { subjectTypeList } from '@/lib/config'
  export default{
    mounted() {
      this.editor = new E('#editorElem')
      // 自定义菜单配置
      this.editor.customConfig.menus = [
        'image',  // 插入图片
        'video',  // 插入视频
        'link',  // 插入链接
      ]
      this.editor.customConfig.uploadImgServer = '/upload'  // 上传图片到服务器
      this.editor.customConfig.onchange = (html) => {
        this.editorContent = html
      }
      this.editor.create()
    },
    computed: {
      letter() {
        let letter = []
        for(let i=0; i<26; i++) {
          letter.push(String.fromCharCode(65 + i))
        }
        return letter
      }
    },
    data() {
      return {
        subjectInitObj: {
          type: 1, // 题型
          question: '', //问题
          answer: ['', '', '', ''], // 答案, 单选多选的答案 数组 length 必须大于 2， 判断题 ['错误', '正确'] 直接用索引 0 1,
          content: '', // 解析内容
          score: 1,  //本题得分
          detailedScore: [], // 详细分值，填空/综合的时候需要配置
          children: [{
            type: 1, // 题型
            question: '', //问题
            answer: [], // 答案
          }],
          status: false
        },
        subject: [],
        err: false, // 用于显示题目边框
        index: null, // 记录subject的index
        radioAnswer: null, //单选 正确答案
        checkboxAnswer: [], // 多选 正确答案
        answerIndex: null, // 多答案记录索引
        modalTitle: {
          question: '设置题干',
          answer: '设置答案',
          content: '设置解析内容'
        },
        modalType: '',
        editor: null,
        editorContent: '',
        editorBool: false,
        knowledge: 0,
        subjectTypeList: subjectTypeList,
        knowledgeList: [{
          label: '组成细胞的分子的构成',
          value: 1
        }],
      }
    },
    methods: {
      //切换题型
      changeType(e, index) {

//      this.$Modal.confirm({
//        title: '提示',
//        content: '修改题型将导致当前设置的答案丢失，是否确认题型修改？',
//        onOk: () => {
//
//        }
//      })
        this.$set(this.subject[index], 'type', e)
        this.$set(this.subject[index], 'question', '')
        this.$set(this.subject[index], 'answer', ['', '', '', ''])
        this.$set(this.subject[index], 'content', '')
        this.$set(this.subject[index], 'score', 1)
        this.$set(this.subject[index], 'detailedScore', [])
        this.$set(this.subject[index], 'children', {
          type: 1, // 题型
          question: '', //问题
          answer: [], // 答案
        })
        this.$set(this.subject[index], 'status', false)
      },
      //删除大题
      handleDel(index) {
        this.subject.splice(index, 1)
      },
      // 清空富文本
      modalCancel() {
        this.editor.txt.clear()
        this.editorContent = ''
      },
      //显示富文本编辑器
      showModal(type, index, idx = null) {
        this.editorBool = true
        this.modalType = type
        this.index = index
        switch (type) {
          case 'question':
            this.editorContent = this.subject[index].question
            break;
          case 'answer':
            this.editorContent = this.resAnswer(index, idx)
            this.answerIndex = idx // 将当前点击的索引记录，编辑后需要匹配
            break;
          case 'content':
            this.editorContent = this.subject[index].content
            break;
          default:
            this.editorContent = ''
            break;
        }
        this.editor.txt.append(this.editorContent)
      },
      // 富文本提交数据
      modalAppend() {
        switch (this.modalType) {
          case 'question':
            this.subject[this.index].question = this.editorContent
            break;
          case 'answer':
            this.subject[this.index].answer[this.answerIndex] = this.editorContent.replace(/<p>(.*?)<\/p>/g,"$1")
            this.answerIndex = null // 还原 answerIndex ，防止出现意外
            this.index = null
            break;
          case 'content':
            this.subject[this.index].content = this.editorContent
            break;
          default:
            this.editorContent = ''
            break;
        }
        this.editorContent = ''
        this.editor.txt.clear()
      },
      // 编辑问题答案选项时，需要根据type判断选项是数组还是文字
      resAnswer(index, idx) {
        // 单选 多选
        const { type, answer } = this.subject[index]
        if([1, 2].indexOf(type) !== -1) {
          return '<p>' + answer[idx] + '</p>'
        }
      },
      // 删除 单选 多选 答案选项
      handleDelAnswer(index, idx) {
        //如果删除时，这个选项被选为正确答案，需要清空下正确答案
        const { type } = this.subject[index]
        if(this.letter[idx] === this.radioAnswer && type == 1) {
          this.radioAnswer = null
        }
        if (type == 2) {
          const i = this.checkboxAnswer.findIndex(pet => pet === this.letter[idx])
          if (i > -1) {
            this.checkboxAnswer.splice(i, 1)
          }
        }
        this.subject[index].answer.splice(idx, 1)
      },
      // 添加一个 单选 多选的 答案选项
      handleAppendAnswer(index) {
        this.subject[index].answer.push('')
      },

      //添加题目
      unshiftSubject() {
        if(this.subject.length) {
          if (!this.subject[0].status) {
            this.err = true
            this.$Message.error('请完成当前新增题型');
            return
          }
        }
        this.subject.unshift(this.subjectInitObj)
      },
    }
  }
</script>
<style scoped>
  .ivu-radio-group-vertical .ivu-radio-wrapper{
    height: inherit !important;
  }
  .subject{
    margin-top: 15px;
    background: #fff;
    padding: 5px 20px;
    position: relative;
    min-height:300px;
    border: 3px solid #fff;
  }
  .subject.error{
    border: 3px solid #ed3f14;
  }
  .subject .active-checkmark{
    position: absolute;
    width: 0px;
    height: 0px;
    z-index:1;
    border-width: 0px 0px 30px 30px;
    border-style: solid;
    top: -3px;
    left: -3px;
  }
  .subject-close{
    position: absolute;
    z-index: 2;
    right: 0px;
    top: 0px;
  }
  .subject-close .ivu-icon{
    height: 30px;
    width: 30px;
    font-size: 16px;
    line-height: 30px;
    text-align: center;
    cursor: pointer;
    -webkit-transform: rotate(0deg);
    -moz-transform: rotate(0deg);
    -ms-transform: rotate(0deg);
    -o-transform: rotate(0deg);
    transform: rotate(0deg);
    transition: all 0.45s;
    -moz-transition: all 0.45s; /* Firefox 4 */
    -webkit-transition: all 0.45s; /* Safari and Chrome */
    -o-transition: all 0.45s; /* Opera */
  }
  .subject-close .ivu-icon:hover{
    -webkit-transform: rotate(90deg);
    -moz-transform: rotate(90deg);
    -ms-transform: rotate(90deg);
    -o-transform: rotate(90deg);
    transform: rotate(90deg);
  }
  .subject .active-checkmark{
    border-color: transparent #e0e0e0;
  }
  .subject.active .active-checkmark{
    border-color: transparent #55bba4;
  }
  .subject .ivu-icon-android-done{
    position: absolute;
    top: -3px;
    left: -3px;
    width: 30px;
    height: 30px;
    z-index: 2;
    line-height: 18px;
    font-size: 16px;
    padding-left: 5px;
    color: #fff;
  }
  .subject .title{
    height: 50px;
    line-height: 50px;
  }
  .subject .title .num{
    width: 30px;
    font-weight: 500;
    text-align: left;
  }
  .mar-r-20{
    margin-right: 20px;
  }
  .question{
    border: 1px dashed #dddddd;
    padding: 10px 15px;
    background: #fbfeff;
    margin-top: 10px;
    border-radius: 5px;
    line-height: 30px;
  }
  .null{
    cursor: pointer;
  }
  .answer{
    padding: 10px;
  }
  .answer-radio li{
    line-height: 30px;
    height: 30px;
  }
  .answer .answer-close{
    margin-left: 15px;
    display: none;
    height: 100%;
    text-align: center;
    cursor: pointer;
  }
  .answer .ivu-radio-wrapper:hover .answer-close, .answer .ivu-checkbox-group-item:hover .answer-close{
    display: inline-block;
  }
  .append-answer{
    margin-top: 5px;
    margin-left: -5px;
  }
  .subject-content{
    padding: 10px;
  }
  .subject-content .title{
    height: 30px;
    line-height: 30px;

  }
  .subject-content .content{
    margin-top: 10px;
  }
  .answer-item *{
    display: inline-block !important;
  }
  .inline .ivu-checkbox-group-item{
    display: block;
    line-height: 30px;
  }
</style>
